﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Security;
using Cms.Application;
using Cms.Application.Admin.Presenters;
using Cms.Application.Admin.Views;
using Cms.Application.IO;
using Cms.Domain;
using Cms.Utilities;
using Cms.Web.Framework.Controls;
using iLib.Web.UI;

namespace Cms.Web.UI.Admin
{
    public partial class EditCustomAdminPage : AdminPage, IEditCustomAdminPageView
    {
        private EditCustomAdminPagePresenter _presenter;

        #region IEditAdminPageView Members

        public int CustomAdminPageId
        {
            get
            {
                if (hidPageID.Value == string.Empty)
                    hidPageID.Value = QueryString.GetInt32ID("id").ToString();
                return int.Parse(hidPageID.Value);
            }
        }

        public void SetCustomAdminPageId(int id)
        {
            hidPageID.Value = id.ToString();
        }

        public string CurrentTab
        {
            get { return tabStrip.CurrentValue; }
        }

        public string Filename
        {
            get { return txtFilename.Text; }
            set { txtFilename.Text = value; }
        }

        public string Name
        {
            get { return txtName.Text; }
            set { txtName.Text = value; }
        }

        public bool ShowInMenu
        {
            get { return chkShowInMenu.Checked; }
            set { chkShowInMenu.Checked = value; }
        }

        public string ContextTranslationFile
        {
            get { return "Admin/Translations/EditCustomAdminPage.xml"; }
        }

        public string XmlTranslations
        {
            get { return hidXmlTranslations.Value; }
            set { hidXmlTranslations.Value = value; }
        }

        public string Code
        {
            get { return hidCode.Value; }
            set { hidCode.Value = value; }
        }

        public string GetSourceCodeStatus()
        {
            string url = UserTempDirectory + "CustomAdminPagePreview.aspx";
            var req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse resp;
            string result = string.Empty;
            req.Method = "GET";
            var cc = new CookieContainer();
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie == null)
            {
                Logging.LogError("GetSourceCodeStatus error: No auth cookie", null);
                return string.Empty;
            }
            var c = new Cookie(authCookie.Name, authCookie.Value, authCookie.Path, Request.Url.Host);
            cc.Add(c);
            req.CookieContainer = cc;
            try
            {
                Logging.LogInfo("GetSourceCodeStatus prepared");
                resp = (HttpWebResponse)req.GetResponse();
                if (resp.StatusCode == HttpStatusCode.OK)
                    result = "ok";
                Logging.LogInfo("No GetResponse exception. Result: " + result);
            }
            catch (WebException ex)
            {
                Logging.LogInfo("Enter catch part");
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    resp = ex.Response as HttpWebResponse;
                    if (resp != null)
                    {
                        Logging.LogInfo("Get Response Stream");
                        var sr = new StreamReader(resp.GetResponseStream());
                        result = sr.ReadToEnd();
                        sr.Close();
                        sr.Dispose();
                        IDiskAccess diskAccess = new DiskAccess();
                        diskAccess.DeleteFile(UserPhysicalTempDirectory + "ErrorDetails.aspx");
                        diskAccess.CreateTextFile(UserPhysicalTempDirectory + "ErrorDetails.aspx", result);
                        result = result.Substring(result.IndexOf("<title>", StringComparison.InvariantCultureIgnoreCase) + 7);
                        result = result.Substring(0, result.IndexOf("</title>", StringComparison.InvariantCultureIgnoreCase));
                    }
                }
            }
            Logging.LogInfo("result: " + result);
            return result;
        }

        public void SetAllowedAdministratorGroups(
            IList<AdministratorGroup> availableGroups,
            IList<AdministratorGroup> inheritedGroups,
            IList<AdministratorGroup> groups)
        {
            gsAllowedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trAllowedAdministratorGroups.Visible = availableGroups.Count > 0;
        }

        public IEnumerable<AdministratorGroup> GetSelectedAllowedAdministratorGroups()
        {
            return gsAllowedAdministratorGroups.GetSelectedGroups();
        }

        public void SetDeniedAdministratorGroups(
            IList<AdministratorGroup> availableGroups,
            IList<AdministratorGroup> inheritedGroups,
            IList<AdministratorGroup> groups)
        {
            gsDeniedAdministratorGroups.SetGroups(availableGroups, inheritedGroups, groups);
            trDeniedAdministratorGroups.Visible = availableGroups.Count > 0;
        }

        public IEnumerable<AdministratorGroup> GetSelectedDeniedAdministratorGroups()
        {
            return gsDeniedAdministratorGroups.GetSelectedGroups();
        }

        #endregion

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            _presenter = new EditCustomAdminPagePresenter(this);
            if (!Page.IsPostBack)
            {
                if (CustomAdminPageId > 0)
                    tabStrip.SelectedValue = Request.QueryString["tab"];
                _presenter.Initialize();
                HeadingIcon = litIcon.Text;
            }
            _presenter.UpdateHeading();
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            tiProperties.OnClientClick = GetClientClickScript(tiProperties);
            tiXmlTranslations.OnClientClick = GetClientClickScript(tiXmlTranslations);
            tiCode.OnClientClick = GetClientClickScript(tiCode);
            if (tabStrip.CurrentValue != tabStrip.SelectedValue && hidSave.Value != "ok")
            {
                _presenter.RefreshPropertiesOnView();
            }
        }

        protected override void OnPreRenderComplete(EventArgs e)
        {
            base.OnPreRenderComplete(e);
            if (tabStrip.SelectedValue == "properties")
            {
                upnlProperties.Update();
            }
            ClientScriptProxy.Current.RegisterStartupScript(
                tabStrip,
                GetType(),
                "updatePanels",
                "updatePanels('" + tabStrip.SelectedValue + "');",
                true);
            upnlButtons.Update();
        }

        protected void tabStrip_Click(string value)
        {
            if ((CurrentTab == "properties" && hidSave.Value == "ok") ||
                (CurrentTab == "xmlTranslations" && hidSaveXmlTranslations.Value == "ok") ||
                (CurrentTab == "code" && hidSaveCode.Value == "ok"))
                _presenter.Save();
            if (_presenter.IsValid)
            {
                ClientScriptProxy.Current.RegisterStartupScript(tabStrip, GetType(), "init", "init();", true);
            }
            upnlXmlTranslations.Update();
            upnlCode.Update();
            upnlProperties.Update();
            upnlTabs.Update();
        }

        protected void lbSave_Click(object sender, EventArgs e)
        {
            _presenter.Save();
        }

        protected void lbSaveAndReturn_Click(object sender, EventArgs e)
        {
            _presenter.Save();
            if (_presenter.IsValid)
            {
                Response.Redirect("CustomAdminPages.aspx");
            }
        }

        private string GetClientClickScript(AdminTabItem ti)
        {
            return "cms.Edit.ShowTabOverlays(); " +
                   "updateCode(); " +
                   "if (isDirty()) {" +
                   "return cms.Dialogs.Confirm(" +
                   "function (status) { " +
                   "document.getElementById('ctl00_body_hidSaveXmlTranslations').value = status;" +
                   "document.getElementById('ctl00_body_hidSaveCode').value = status;" +
                   "document.getElementById('ctl00_tabs_hidSave').value = status;" +
                   "var pageID = document.getElementById('ctl00_tabs_hidPageID').value;" +
                   "if ((pageID == '' || pageID == '-1') && status != 'ok') " +
                   "cms.Edit.HideTabOverlays(); " +
                   "else " +
                   "__doPostBack('" + ti.UniqueID + "$" + ti.ID + "','');" +
                   "}, " +
                   "'" + GetText(this, "SaveInfoHeader") + "', " +
                   "'" + GetText(this, GetSaveInfoMessageKey()) + "', " +
                   "'" + GetText(this, "SaveInfoOK") + "', " +
                   "'" + GetText(this, "SaveInfoCancel") + "', " +
                   "true, " +
                   "null" +
                   ");" +
                   "}";
        }

        private string GetSaveInfoMessageKey()
        {
            return CustomAdminPageId > 0 ? "OptionalSaveInfoMessage" : "ForceSaveInfoMessage";
        }
    }
}